package back.service.impl;

import back.dao.BackDao;
import back.service.BackService;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import cn.hutool.system.SystemUtil;
import cn.hutool.system.oshi.OshiUtil;
import com.alibaba.fastjson.JSON;
import common.collect.BaseCollectUitls;
import common.jdbc.BaseDBUtils;
import common.spring.ClassPathXmlApplicationContext;
import oshi.hardware.HWDiskStore;
import pojo.*;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 马泽朋
 * @version 1.0
 * @date 2019/10/20 11:19
 */
public class BackServiceImpl implements BackService {
    private static BackDao backDao;
    private static ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "spring/ApplicationContext-dao.xml");
    static {
        try {
            backDao = (BackDao) context.getBean(BackDao.class.getSimpleName());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 根据账号密码登录后台
     *
     * @param map
     */
    @Override
    public Map<String, Object> loginbackgroundByaccountAndpassword(Map<String, Object> map) {
        Map<String, Object> map1 = new HashMap<>();
        try {
            //从集合中取出密码
            String password = (String) map.get("password");
            //拿到加密对象
            Digester md5 = new Digester(DigestAlgorithm.MD5);
            //对密码进行MD5加密，与数据库中的密码进行对比
            String digestHex = md5.digestHex(password);
            //重新put到map中
            map.put("password", digestHex);
            Management management = backDao.loginbackgroundByaccountAndpassword(map);
            map1.put("code",0);
            map1.put("msg", "登入失败");
            if (null != management){
                map1.put("msg","登入成功");
                map1.put("management", management);
                map1.put("token",md5.digestHex(JSON.toJSONString(management)));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return map1;
    }

    /**
     * 采集小说入库
     *
     * @param map
     * @return
     */
    @Override
    public List<Integer> collectionOfSingleNovelLibrary(Map<String, Object> map) {


        //获得需要爬取的主域名
        String domain = (String) map.get("domain");

        //请求的列表地址
        String url = (String) map.get("url");

        //获得爬取的起始位置
        int start = (int) map.get("start");

        //获得结束位置
        int end = (int) map.get("end");

        //获得小说单本采集html规则
        String chapterRules = (String) map.get("chapterRules");

        //调用工具类生成起始url集合
        List<String> chapterSet = BaseCollectUitls.getChapterSet(url,start,end);

        //遍历集合开始采集url
        for (String s : chapterSet) {
            //开启事务
            try {
                BaseDBUtils.startTransaction();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            //返回单本小说url地址和分配到的唯一uuid
            // 注：【此地址无主域名】
            Map<String, Object> theBookAddress = BaseCollectUitls.getTheBookAddress(chapterRules, s);
            try {

                //开始入库
                Map<String, Object> map1 = backDao.collectionOfSingleNovelLibrary(theBookAddress);

                //提交事务，不关闭连接下次继续调用
                BaseDBUtils.commitAndClose();
            } catch (SQLException e) {
                e.printStackTrace();
                try {
                    //如果SQL出现异常回滚数据库
                    BaseDBUtils.RollbackAndclose();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }
        try {
            BaseDBUtils.closeAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //拿到分类信息

        List<Classification> classifications = null;
        try {
            //分类信息
            classifications = backDao.queryClassification(null);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //采集小说简略信息，并保存章节
        try {
            //采集简略信息结果
            List<Book> books=null;
            //采集的章节信息
            List<Chapter> chapters=null;

            int num = 0;
            do {
                //分页的位置
                int index = num*1000;
                //从数据库拿到地址
                List<CollectSingle> collectSingles = backDao.collectTheBasicInformationOfTheNovel(index);
                //看一下拿到的记录
                System.out.println(collectSingles.size());
                //采集的简略信息
                books = BaseCollectUitls.collectBriefInformationAndChapters(domain, collectSingles, classifications);
                //采集章节信息
                chapters = BaseCollectUitls.collectionChapter(domain, collectSingles);

                //采集小说文本
                List<NovelText> novelTexts = BaseCollectUitls.collectionNovelText(domain,chapters);

                //每一次起始位置加上1然后乘以1000
                num ++;
                //放入数据库的结果
                Map<String, Object> map3 = backDao.collectionNovelText(novelTexts);
                Map<String, Object> map2 = backDao.collectionChapter(chapters);
                Map<String, Object> map1 = backDao.collectingNovelInformationIntoTheLibrary(books);
            }while (books.size() > 0);

        } catch (SQLException | IOException e) {
            e.printStackTrace();
        }



        return null;
    }

    /**
     * 查询主页一般信息
     *
     * @return
     */
    @Override
    public String homePageInformationQuery() {
        String message = null;
        try {

            Map<String, Object> map = backDao.homePageInformationQuery();
            map.put("info", SystemUtil.getRuntimeInfo());
            HWDiskStore[] diskStores = OshiUtil.getDiskStores();
            for (HWDiskStore diskStore : diskStores) {
                System.out.println(diskStore.getSize());
            }
            message = JSON.toJSONString(map);

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return message;
    }

    /**
     * 查询小说后台列表
     *
     * @param map
     * @return
     */
    @Override
    public Map<String, Object> novelist(Map<String, Object> map) {
        try {
            //储存了查询结果
            Map<String, Object> novelist = backDao.novelist(map);
            Map<String, Object> map1 = backDao.homePageInformationQuery();
            List<Book> list = (List<Book>) novelist.get("list");
            String s = JSON.toJSONString(list);
            System.out.println(s);
            Map<String, Object> map2 = new HashMap<>();
            map2.put("code", 0);
            map2.put("msg", "");
            map2.put("count", map1.get("all"));
            map2.put("data",list );

            return map2;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


}
